self.addEventListener('message', async (event) => {
  // const 
  const { data } = event;
  const fileName = await getFileName(data)
  self.postMessage(fileName)
})


async function getFileName (file) {
  const fileHash = await calculateFileHash(file);
  // 文件名
  const fileExtension = file.name.split('.').pop();
  return `${fileHash}.${fileExtension}`
}


async function calculateFileHash (file) {
  console.log(file)
  const arrayBuffer = await file.arrayBuffer()
  // crypto.subtle.digest加密
  const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
  // hashBuffer 是二进制,需要转十进制
  return bufferToHex(hashBuffer)
}

// 将一个arrayBuffer 转成16进制的字符串
function bufferToHex (hashBuffer) {
  // buffer转字符串
  return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('')
}